package com.yeskery.nut.util.logging;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Nut日志格式化
 * @author sprout
 * @version 1.0
 * 2022-09-12 14:38
 */
public class NutLoggingFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
        String source;
        if (record.getSourceClassName() != null) {
            source = record.getSourceClassName();
            if (record.getSourceMethodName() != null) {
                source += "(" + record.getSourceMethodName() + ")";
            }
        } else {
            source = record.getLoggerName();
        }
        String throwable = "";
        if (record.getThrown() != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.println();
            record.getThrown().printStackTrace(pw);
            pw.close();
            throwable = sw.toString();
        }
        Thread thread = Thread.currentThread();
        return String.format("%1$tF %1$tT.%1$tL [%2$s] [%3$s] %4$s: %5$s%6$s%n",
                new Date(record.getMillis()),
                record.getLevel().getName(),
                thread.getName(),
                source,
                record.getMessage(),
                throwable
        );
    }
}
